<div class="image-dialog" id="dialog">
    <div class="image-dialog-head">
        <label class="pull-left flex">
            <input class="layui-input margin-right-5" v-model="keyword" style="height:30px;line-height:30px"
                   placeholder="{:lang('请输入搜索关键词')}">
            <a class="layui-btn layui-btn-sm layui-btn-normal" @click="search">{:lang('搜 索')}</a>
        </label>
        <div class="pull-right">
            <a class="layui-btn layui-btn-sm layui-btn-normal" @click="close">确定</a>
        </div>
    </div>
    <div class="image-dialog-body" :id="id" style="width: 100%; height: 500px"></div>
</div>


<style>
    .layui-layer-page .layui-layer-content {
        overflow: hidden;
    }
</style>
<script>
    require(['jquery', 'vue', 'qqmap'], function ($, vue) {
        var app = new vue({
            el: '#dialog',
            data: {
                didx: 0,//弹窗索引
                keyword: '',
                idx: 0,
                id: 'container',
                lng: '',
                lat: '',
                district_code: '',
                address: '',
                mapMarker: null,
                apiKey: 'M7YBZ-PYJLJ-5U7FS-DKVV5-TRB4T-APFP3',
            },
            methods: {
                getJson: function (url, func, callback) {
                    window[func] = function (data) {
                        callback(data);
                    };
                    let script = document.createElement("script");
                    script.setAttribute("src", url);
                    document.getElementsByTagName("head")[0].appendChild(script);
                    script.onload = script.onreadystatechange = function (data) {
                        window[func] = null;
                    };
                },
                search: function () {
                    let self = this;
                    let url = encodeURI(
                        "https://apis.map.qq.com/ws/geocoder/v1/?address=" + encodeURI(this.keyword) + "&boundary=region(" + this.keyword + ",0)&page_size=9&page_index=1&key=ZI5BZ-N5667-YRLX5-HT23K-QWQJ2-FIFCF&output=jsonp&&callback=?"
                    );
                    self.getJson(url, "QQmap", function (res) {
                        console.log("res", res)
                        if (res.status === 0) {
                            res = res.result;
                            self.lat = res.location.lat;
                            self.lng = res.location.lng;
                            self.address = res.address;
                            self.district_code = res.ad_info.adcode;
                            window['getJson'] = null;
                            self.setInput();
                            // $.msg.close(self.didx);
                        }
                    });

                },
                close: function () {
                    $.msg.close(this.didx);
                },
                // 设置选择数据
                setValue: function (xurl) {
                    $.msg.close(this.didx);
                    this.$btn.triggerHandler('push', xurl);
                    return this;
                },

                initMap: function () {
                    let self = this;
                    let center = new TMap.LatLng(39.916527, 116.397128);
                    if (self.lng && self.lat) {
                        center = new TMap.LatLng(self.lat, self.lng);
                    }
                    const map = new TMap.Map(self.id, {
                        zoom: 15, // 设置地图缩放
                        center: center, // 设置地图中心点坐标，
                        pitch: 0, // 俯仰度
                        rotation: 0, // 旋转角度
                    });
                    console.log("map", TMap)
                    //地图标记
                    const markerArr = [];
                    if (self.lat && self.lng) {
                        markerArr.push({
                            "id": "marker3",
                            "styleId": 'marker',
                            "position": new TMap.LatLng(self.lat, self.lng),
                            "properties": {"title": "marker3"}
                        });
                    }
                    //初始化marker图层
                    let marker = new TMap.MultiMarker({
                        id: 'marker-layer',
                        position: center,
                        map: map,
                        geometries: markerArr,
                    });
                    //监听点击事件添加marker
                    map.on("click", (evt) => {
                        marker.setGeometries([
                            {
                                id: 'marker3',
                                position: evt.latLng
                            }
                        ]);
                        let lat = evt.latLng.getLat(),
                            lng = evt.latLng.getLng();
                        let url = encodeURI(`https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=${self.apiKey}&output=jsonp&&callback=?`)
                        self.getJson(url, "QQmap", function (res) {
                            console.log("res", res)
                            if (res.status === 0) {
                                res = res.result;
                                self.lat = res.location.lat;
                                self.lng = res.location.lng;
                                self.address = res.address;
                                self.district_code = res.ad_info.adcode;
                                window['getJson'] = null;
                                self.setInput();
                                // $.msg.close(self.didx);
                                // self.$btn.triggerHandler('push', "666666666")

                            }
                        });
                    });
                },
                setInput: function () {
                    if (this.$btn.data('lat')) {
                        $(this.$btn.data('lat')).val(this.lat).trigger('change');
                    }
                    if (this.$btn.data('lng')) {
                        $(this.$btn.data('lng')).val(this.lng).trigger('change');
                    }
                    if (this.$btn.data('address')) {
                        $(this.$btn.data('address')).val(this.address).trigger('change');
                    }
                    if (this.$btn.data('code')) {
                        $(this.$btn.data('code')).val(this.district_code).trigger('change');
                    }
                },
                onMapSearch() {
                    let self = this;
                    var url =
                        "https://apis.map.qq.com/ws/geocoder/v1/?address=" +
                        encodeURI(this.addr) +
                        "&key=M7YBZ-PYJLJ-5U7FS-DKVV5-TRB4T-APFP3" +
                        "&output=jsonp&&callback=?";
                    // let url = encodeURI(
                    //   "https://apis.map.qq.com/ws/geocoder/v1/?address=" +
                    //     encodeURI(this.form.address_detail) +
                    //     "&boundary=region(" +
                    //     this.form.address +
                    //     ",0)&page_size=9&page_index=1&key=ZI5BZ-N5667-YRLX5-HT23K-QWQJ2-FIFCF&output=jsonp&&callback=?"
                    // );
                    getJson(url, "QQmap", (res) => {
                        if (!res.result) {
                            console.log('查询结果res===》', res)
                            return;
                        }
                        let result = res.result;
                        console.log('查询结果addr===》', result)

                        // self.lat = result.location.lat;
                        // self.lon = result.location.lng;
                        //通知父组件 防止prop变异
                        var listenData = {lat: result.location.lat, lon: result.location.lng}
                        // this.$emit('chooseListenMap', listenData);

                        self.map.zoomTo(20);
                        self.map.panTo(
                            new qq.maps.LatLng(result.location.lat, result.location.lng)
                        );
                        let latlng = new qq.maps.LatLng(
                            result.location.lat,
                            result.location.lng
                        );
                        if (self.mapMarker) {
                            self.mapMarker.setMap(null);
                            self.mapMarker = null;
                        }
                        self.mapMarker = new qq.maps.Marker({
                            map: self.map,
                            position: latlng,
                            zIndex: 10,
                        });
                        self.mapMarker.setTitle(result.title);
                        /*给图标加事件*/
                        qq.maps.event.addDomListener(self.mapMarker, "click", function (e) {
                            self.choseItem(result);
                        });
                        return;
                        for (let n = 0; n < res.data.length; n++) {
                            self.map.zoomTo(20);
                            if (n == 0) {
                                self.map.panTo(
                                    new qq.maps.LatLng(
                                        res.data[0].location.lat,
                                        res.data[0].location.lng
                                    )
                                );
                            }
                            let ele = res.data[n];
                            // console.log("ele", ele);
                            let latlng = new qq.maps.LatLng(ele.location.lat, ele.location.lng);
                            let left = n * 27;
                            let marker = new qq.maps.Marker({
                                map: self.map,
                                position: latlng,
                                zIndex: 10,
                            });
                            marker.index = n;
                            marker.isClicked = false;
                            marker.setTitle(ele.title);
                            self.markerPoint(marker, true);
                            /*给图标加事件*/
                            qq.maps.event.addDomListener(marker, "click", function (e) {
                                //console.log('点击地图',e.target.index);
                                self.choseItem(self.searchList[e.target.index], e.target.index);
                            });
                        }
                    });
                },
                choseItem(item) {
                    console.log('选择坐标===》', item)
                    // this.form.lat = item.location.lat;
                    // this.form.lon = item.location.lng;

                    //通知父组件 防止prop变异
                    var listenData = {lat: item.location.lat, lon: item.location.lng}
                    // this.$emit('chooseListenMap', listenData);

                    console.log("chose", item);
                    let self = this;
                    // self.select_address = _index;
                    self.map.panTo(new qq.maps.LatLng(item.location.lat, item.location.lng));
                    self.map.zoomTo(20);
                }


            },
            created: function () {
                this.didx = $.msg.mdx.pop();
                this.$btn = $('#{$get.id|default=""}');
                if (this.$btn.data('lat')) {
                    this.lat = $(this.$btn.data('lat')).val();
                }
                if (this.$btn.data('lng')) {
                    this.lng = $(this.$btn.data('lng')).val();
                }
                console.log("btn", this.$btn)
            },
            mounted() {
                this.$nextTick(() => {
                    this.initMap();
                })

            },
        });
    });
</script>